package com.trackerapp.screen;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.trackerapp.R;
import com.trackerapp.network.HttpConnection;
import com.trackerapp.util.MessageUtil;
import com.trackerapp.util.TrackerPreferenceManager;

public class RegisterAccessCodeActivity extends Activity {

	Button register;
	EditText phoneEdit;
	EditText accesscodeEdit;
	String regId;
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.register_layout);
		register = (Button) findViewById(R.id.register);
		phoneEdit = (EditText) findViewById(R.id.phone_edit);
		accesscodeEdit = (EditText) findViewById(R.id.access_edit);
		Bundle extras = getIntent().getExtras();
		if (extras == null) {
			System.out.println(" ON create NULL REG ID ########## ");
			regId = " NULL REG ID";
		}else {
			regId = extras.getString("gcmid");
		}
		System.out.println(" ON create ########## "+regId);
		register.setOnClickListener(new View.OnClickListener() {			
			@Override
			public void onClick(View v) {
				System.out.println(" ### onclick ##### ");
				verifyCode();
			}
		});
	}
	
    final Handler registerHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case HttpConnection.REQUEST_START:
                	System.out.println(" #### START ######## ");
                    break;
                case HttpConnection.REQUEST_SUCCEED:
                	String result = (String) msg.obj;
                	System.out.println(" #### SUCESS ######## "+result);
                	try {
                		JSONArray data = new JSONArray(result);
                		
                		// Check for http status code.
                		JSONObject httpStatusJson = data.getJSONObject(0);
                		String httpStatus = httpStatusJson.getString("status");
                		if( httpStatus.equals("200")) {                			
                			// Get user_id, device_id, session_id.
                			int user_id = data.getJSONObject(1).getInt("user_id");
                			int device_id = data.getJSONObject(1).getInt("device_id");
                			int session_id = 0;
                			if( data.getJSONObject(1).has("session_id"))
                				session_id = data.getJSONObject(1).getInt("session_id");
                			
                			System.out.println(" User id : "+user_id+" : Device id : "+device_id+" : session_id : "+session_id);
                			TrackerPreferenceManager.setString(TrackerPreferenceManager.PreferenceKeys.USER_ID, Integer.toString(user_id));
                			TrackerPreferenceManager.setString(TrackerPreferenceManager.PreferenceKeys.DEVICE_ID, Integer.toString(device_id));
                			TrackerPreferenceManager.setString(TrackerPreferenceManager.PreferenceKeys.SESSION_ID, Integer.toString(session_id));
        	        		Intent userIntent = new Intent(RegisterAccessCodeActivity.this,TrackDeliveryActivity.class);
        	        		userIntent.putExtra("gcmid", regId);
        	        		RegisterAccessCodeActivity.this.startActivity(userIntent);
        	        		finish();

                		} else if(httpStatus.equals("422") || httpStatus.equals("404") || httpStatus.equals("401")) {
                			showErrorDialog("ERROR",data.getJSONObject(1).getString("errorcode"), data.getJSONObject(1).getString("error")+data.getJSONObject(1).getString("extra_info"));
                		} else {
                			
                		}
                	} catch(Exception e) {
                		e.printStackTrace();
                	}                	
                	
                    break;
                case HttpConnection.REQUEST_ERROR:                    
                    MessageUtil.showMessage((String) msg.obj, false);
                    break;
                case HttpConnection.INVALID_SESSION:
                	System.out.println(" #### INVALID SESSION ######## ");
                    break;
            }
        }

    };
	
    private void showErrorDialog(String title,String errorCode, String errorMessage) {
    	
    	new AlertDialog.Builder(this)
        .setTitle(title)
        .setMessage(errorCode+" : "+errorMessage)
        .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) { 
                // continue with delete
            }
         }).show();
    }
	
    
    private void verifyCode() {
		System.out.println(" ##### verifycode ##### ");
        HttpConnection connection = new HttpConnection(registerHandler);

        String url = "http://ec2-54-242-153-20.compute-1.amazonaws.com:3000/verify_accesscode";

        connection.addHeader("Accept", "application/xml");
//        connection.addCookie("_session_id", session);

        connection.addParam("phonenumber", phoneEdit.getText().toString());
        connection.addParam("accesscode", accesscodeEdit.getText().toString());
        connection.addParam("push_notification_id", regId);
        connection.addParam("device_os", "android");
        connection.post(url);

	}
	
}